"""
导入设备参数文件：
名称：
dataInput_Lidar02_RamT.csv
dataInput_Lidar02_RayT.csv
dataInput_Lidar02_RayW.csv
dataInput_Lidar02_ResW.csv

名称提供两个信息：
设备名称：Lidar02
探测体制：RamT、RayT、RayW、ResW

"""
#coding=utf-8
import os
import pandas as pd
import numpy as np
from utils.mylib_db import *
from utils.mylib_utils import *
from measurement.measurement_utils import *
from measurement.import_probe_data_into_db import *

# 设备参数字典表
db_dict_device_parameter_table = "bt_dict_device_system_type"
db_dict_system_type_table = "bt_dict_system_type"
# 设备参数保存表
db_device_parameter_table = "bt_device_system_type"

def readDeviceParameterDataFile(param):
    """
    导入设备参数文件
    """
    print("导入设备参数文件..")
    print(param)
    file_path = param.get('file_path')
    user_id = int(param.get('user_id'))

    if file_path.strip() == '':
        print("参数错误！")
        return {"code":-1, "msg": "参数错误"}
    if not os.path.isfile(file_path):
        print("文件不存在！")
        return {"code": -1, "msg": "文件不存在"}

    # 分离路径、文件名
    (filepath, tempfilename) = os.path.split(file_path)
    print("路径：%s; 文件名：%s" % (filepath, tempfilename))
    #分离文件名、文件后缀
    #(filename, extension) = os.path.splitext(tempfilename)
    #print("文件名：%s; 扩展名：%s" % (filename, extension))

    # 解析文件名并获取设备ID
    device_name, system_type = getDeviceInfoFromFileName(tempfilename)
    print(device_name, system_type)
    device_name_list = getAlignDeviceName(device_name)
    # device_info = getDeviceInfo(device_name)
    device_info = getDeviceInfoByDeviceNameList(device_name_list)
    if device_info != "":
        device_id = device_info[0]
        print(device_id)
    else:
        print("未找到设备信息")
        return {"code": -1, "msg": "设备信息未在库中"}

    # 获取所有参数信息加入到字典备查
    device_parameter_dict = getParameterInfoFromDb()
    # print(device_parameter_dict)
    # 获取所有体制信息备查
    system_type_dict = getDeviceSystemTypeFromDb()
    # print(system_type_dict)

    # 读取设备参数数据
    # header=0使用第一行作为列索引
    df = pd.read_csv(file_path, header=0, encoding='gb18030')
    # print(df)

    #插入数据库
    db_cols = ["DeviceId", "SystemType", "ParameterId", "Parameter", "Value", "Unit", "Distribution"]
    value_arr = []
    for i in range(len(df['参数'])):
        param_name = df['参数'][i]
        print(param_name)
        param_id = getParameterId(device_parameter_dict, param_name)
        if param_id == -1:
            print("设备参数名称错误！")
            return {"code": -1, "msg": "设备参数名称错误！"}
        system_type_id = getSystemTypeId(system_type_dict, system_type)
        if system_type_id == -1:
            print("设备探测体制名称错误！")
            return {"code": -1, "msg": "设备探测体制名称错误！"}

        value = getFieldValue(df['数值'][i])
        unit = getFieldValue(df['单位'][i])
        distribute = getFieldValue(df['分布（不确定度）'][i])

        query_conditon = 'DeviceId=%d AND SystemType=%d AND ParameterId=%d AND Parameter="%s"' % \
                        (device_id, system_type_id, param_id, param_name)
        ret = select_db(db_device_parameter_table, query_conditon)
        #print(ret, len(ret))
        if len(ret) > 0:
            update_str = 'Value = "%s", Unit = "%s", Distribution = "%s"' % (value, unit, distribute)
            print("更新数据头状态： %s" % (update_str))
            update_db(db_device_parameter_table, update_str, query_conditon)
        else:
            value_str = '"%d", "%d", "%d", "%s", "%s", "%s", "%s"' % \
                        (device_id, system_type_id, param_id, param_name, value, unit, distribute)
            value_arr.append(value_str)
            # ret = insert_db_in_batch(db_device_parameter_table, db_cols, value_arr)
            # value_arr = []

    if len(value_arr) > 0:
        # ret = insert_db_in_batch(db_device_parameter_table, db_cols, value_arr)
        ret = update_db_in_batch(db_device_parameter_table, db_cols, value_arr)

    # log记录
    saveReadFileLog(user_id, filepath, tempfilename, device_id, device_name, 0)

    return 0


def getFieldValue(value):
    if value == "":
        return ""
    elif pd.isnull(value):
        return ""
    else:
        return value

def getDeviceInfoFromFileName(tempfilename):
    """
    检查文件名格式，解析不出来就算是错的，如切割完的元素个数不对，数据类型不在列表范围中
    返回参数：
        1.文件名称是否合理; True False
        2.探测体制: 文件名称中的体制信息（只有在文件名合法的情况下存在）
    """
    arr = re.split("_+", tempfilename)
    print(arr)
    #文件名格式错误
    if len(arr) != 3:
        print("文件名解析错误：%s" % file_path)
        return [False, ""]

    # 获取设备名称，探测体制
    device_name = arr[1].strip()
    system_type = arr[2].split('.')[0].strip()

    return device_name, system_type


# 获取设备参数名称信息
def getParameterInfoFromDb():
    query_conditon = 'True'
    print("query_conditon: %s" % query_conditon)
    ret = select_db(db_dict_device_parameter_table, query_conditon)
    # print(ret, len(ret))
    if len(ret) > 0:
        ret = dbQueryResult2JsonObj(ret, db_dict_device_parameter_table)
        ret_dict = {}
        for obj in ret:
            ret_dict[obj['ParameterName']] = obj
        return ret_dict
    else:
        return ""


def getParameterId(device_parameter_dict, param_name):
    if device_parameter_dict == "":
        print("未找到设备参数列表数据！")
        return ""

    if param_name in device_parameter_dict.keys():
        param_id = device_parameter_dict[param_name]['Id']
    else:
        print("设备参数名称不存在！")
        return -1

    return param_id


# 通数据库表 bt_dict_system_type
def getDeviceSystemTypeFromDb():
    """
    DeviceSystemType = {
        "RamT": {"Id": 0, "SystemType": "拉曼测温", "SystemTypeCode": "RamT"},
        "RayT": {"Id": 1, "SystemType": "瑞利测温", "SystemTypeCode": "RayT"},
        "RayW": {"Id": 2, "SystemType": "瑞利测风", "SystemTypeCode": "RayW"},
        "ResW": {"Id": 3, "SystemType": "共振荧光测温测风", "SystemTypeCode": "ResW"},
    }
    """
    query_conditon = 'True'
    print("query_conditon: %s" % query_conditon)
    ret = select_db(db_dict_system_type_table, query_conditon)
    # print(ret, len(ret))
    if len(ret) > 0:
        ret = dbQueryResult2JsonObj(ret, db_dict_system_type_table)
        ret_dict = {}
        for obj in ret:
            ret_dict[obj['SystemTypeCode']] = obj
        return ret_dict
    else:
        return ""


# 通过体制代码查询设备体制编号
def getSystemTypeId(device_system_type, system_type_code):
    if device_system_type == "":
        print("未找到设备参数体制列表数据！")
        return ""

    if system_type_code in device_system_type.keys():
        system_type_id = device_system_type[system_type_code]['Id']
    else:
        print("设备参数体制不存在！")
        return -1

    return system_type_id


def getAlignDeviceName(device_name):
    """
    获取设备所有别名
    """
    print(device_name)
    ret_list = [device_name]
    if device_name == "Lidar II":
        ret_list.append("Lidar02")
    if device_name == "Lidar02":
        ret_list.append("Lidar II")

    return ret_list
